import os
import tornado.ioloop
import tornado.web
from tinyesb.http_port import MessageHandler
from scopt.util import message as msg_util


def start(core_port, core_url, app_root, gui_name, channel):
    port = HttpInGuiPort(core_port, core_url, app_root, gui_name, channel)
    port.start()


class HttpInGuiPort:
    def __init__(self, core_port, core_url, app_root, gui_name, channel):
        self.__core_port = core_port
        self.__core_url = core_url
        self.__ioloop = None
        self.__gui_name = gui_name
        self.__app_root = app_root
        self.__channel = channel

    def start(self):
        self.__channel.init()
        print('HTTP I2 PORT(Tornado): Pid {0}, port {1}.'
                .format(os.getpid(), self.__core_port))
        gui_root = os.path.join(self.__app_root, 'ui', self.__gui_name)
        settings = {
            "static_url_prefix": "/ui/",
            "static_path": gui_root,
        }
        application = tornado.web.Application([
            (r"/", WelcomeHandler),
            (r"/ui", tornado.web.StaticFileHandler,
             dict(path=settings['static_path'])),
            (self.__core_url, MessageHandler,
             dict(channel=self.__channel,
                  in_data_factory=_in_data_factory,
                  out_data_factory=_out_data_factory,
                  is_debug_enabled=True,)),
        ], **settings)
        application.listen(self.__core_port)
        print('HTTP I2 PORT(Tornado): About to start IOLoop.')
        self.__ioloop = tornado.ioloop.IOLoop.instance()
        self.__ioloop.start()
        self.__ioloop.close()


class WelcomeHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect("/ui/index.html")


def _in_data_factory(request_handler, is_debug_enabled):
    raw_request = request_handler.get_argument('m', default=None)

    if is_debug_enabled:
        print('--->>> {0}'.format(raw_request.encode('UTF-8')))

    return msg_util.in_data_packet(raw_request)


def _out_data_factory(data_packet, is_debug_enabled):
    raw_response = data_packet['message']['raw_response']

    if is_debug_enabled:
        print('<<<--- {0}'.format(raw_response.encode('UTF-8')))

    return raw_response
